define(function (require, exports, module) {
    var myPub = require('./public');

    var oWindow = $(window);                        // window
    var oContain = $('.js_contain');                // 大盒子
    var oHeader = $('.js_headerBox');               // 头部盒子
    var oFooter = $('.js_footer');                  // 页面底部
    var oGoTop = $('.js_goTop');                    // 回到顶部
    var oSideBox = $('.js_sideBox');		        // 侧边按钮框

    var oGoods_showTwo = $('.js_goods_showTwo');	//并排产品
    var oShowBusiness = $('.js_ShowBusiness');		//商家简介查看更多
    var oBusiness_intro = $('.js_business_intro');	//商家简介说明
    var oCloseBtn = $('.js_closeBtn');				//遮罩关闭按钮

    var oStoreTab = $('.js_storeTab');           //底部tab切换

    var oCategoryAllList = $('.js_categorysAllList');
    var oStoreBoxTop = $('.js_storeBoxTop');   //顶部商家信息
    var oStoreCategory = $('.js_storeCategory');   //商品分类部分
    var oStoreTabCon = $('.js_storeTabCon');     //全部商品和商品分类的内容
    var oCatesBox = $('.js_categorysBox');       //右边子分类盒子

    // var oStoreCon = $('.js_storeContent');


    var oSildeNavJRoll = new myPub.ScrollBar();

    var styleTitle = 'width:100%;  border:none';
    var _sBossInfo= $('.js_bossInfo');
    var _BossName = $('.js_bossName').text();

    // 分类容器
    var oCategorysNavList = $('.js_categorysNavList');
    var oCateGoryLeftList = $('.js_categoryLeftList');

    // 添加商家优惠券领取用法
    var oSellerCoupon = $('.js_sellerCoupon').find('.js_sellerCon');
    var dbTapOff = true;                                         // 阻止多次点击
    var time_tapOff;

    var lazLoading = new myPub.lazLoadingImg();

    var storeGoodsUrl = '/supplier/recommend ';
    var storeCateUrl =   '/supplier/choice/category';

    var resizeTimer = null;



    oShowBusiness.on('click',function() {
        oBusiness_intro.stop().animate({'height':100+'%'},300);
        $('.wrap').addClass('mohu');
    });

    oCloseBtn.on('click',function(e) {
        oBusiness_intro.stop().animate({'height':0+'%'},300);
        $('.wrap').removeClass('mohu');
        e.stopPropagation()
    });

    $('.js_contactBoss').on('click',function(e) {
        myPub.TipTitleLayer('联系商家： '+_BossName,styleTitle, _sBossInfo.html(),function() {
            _sBossInfo.hide();
        });
        e.stopPropagation()
    });

    //底部tab切换
    oStoreTab.on('click',function (e) {
        var sIndex = $(this).attr('sIndex') * 1;
        storeData.tabIndex = sIndex;
        //点击切换选中的tab，0为全部商品，1为商品分类
        oStoreTab.removeClass('active').eq(sIndex).addClass('active');
        oStoreTabCon.hide().eq(sIndex).show();
        //如果商品分类点击
        if(sIndex == 1){
            // oContain.removeClass('overScroll');
            //判断是否已经加载过了
            if(storeData.firstLoadArr[1]){
                storeData.getStoreCateData();
            }
            //商品分类左边的滚动
            if(oSildeNavJRoll.obj === undefined) {
                return;
            }
            else {
                oSildeNavJRoll.ReScroll();
            }
        }

    });


    // 回到过顶部
    oGoTop.on('click', function (e) {
        // oSideBox.hide().stop().animate({'right': '-3.5rem'}, 300);
        oContain.eq(0).stop().animate({scrollTop: '0'}, 250);
        e.stopPropagation();
    });

    // 点击导航展示对应容器
    oCategoryAllList.hammer().on('tap', function (e) {
        var tar = e.gesture.target;
        var $target = $(tar);
        var slideNum,slideNetNum;

        if(tar.tagName.toLowerCase() == 'li') {
            if($target.hasClass('categoryLeftNav')) {
                var index = $target.index();

                //记住最新点击的左侧导航索引
                storeData.catePageNum = index;
                //当点击导航时初始化slider滑动索引
                // storeData.cateSlideNum = 0;

                oCategorysNavList.find('li').removeClass('active');
                $target.addClass('active');
                oCatesBox.find('.js_categorysDetail').hide().eq(index).show();
                // oCategorysBox.find('.js_categorysDetail').hide().eq(index).show();


            }
        }

        // var rightGoodsNav = $target.parents('.jsCategoryRightNav');
        // if(rightGoodsNav.length > 0){
        //     var curIndex = rightGoodsNav.find('.jsHrefCategory').attr('data-curIdx');
        //     if(curIndex == null){
        //         curIndex = 0;
        //     }
        //     sessionStorage.setItem("cateDetPageNum", curIndex);
        //     sessionStorage.setItem("cateDetSlideNum", 0);
        // }
    });




    module.exports = {
        init: function (data, name) {
            storeData.GetSessionData();
            storeData.initEvent();
            storeData.initStore();

            //异步获取优惠券
            storeData.getCouponEvent();

            storeData.couponSwiper();

            // 页面尺寸修改
            oWindow.on('resize', function () {
                if (resizeTimer) {
                    clearTimeout(resizeTimer)
                }
                resizeTimer = setTimeout(function () {
                    storeData.initStore(true);
                    // coAjax.SetSildeNavScroll();
                }, 400);

            });


            // 页面跳转记录数据
            oWindow.unload(function(){
                coAjax.setSession();
            });

        }
    };


    var storeData = {
        catePageNum: 0,  //
        mySwiper: null,  //优惠券swiper
        allGoodsList: [],  //所有的商品列表
        start: 0,         //商品开始的索引
        limit: 10,       //商品每次请求的数量
        time_Scroll: null, //定时器
        loadComplete: false,  //是否加载完成
        firstLoadArr: [true,true], //判断两个tab是否第一次加载
        tabIndex: 0,   //当前tab索引
        cateGoryList: [],   //分类列表
        initEvent: function () {

            // myPub.SetImgHeight(oGoods_showTwo);
            //加载就去
            storeData.scrollLoad();
            //先隐藏返回顶部
            oSideBox.stop().animate({'right': '-3.5rem'}, 300);


        },
        initStore: function (bOff) {
          var _this = this;
          //设置分类内容的高度
          var oCateH = oContain.height() - oStoreBoxTop.outerHeight();

          oStoreCategory.css({height: oCateH});

          if(bOff){

              oContain.css({
                  'padding-top': oHeader.outerHeight(true),
                  'padding-bottom': oFooter.outerHeight(true)
              });

              //分类的滚动
              if(oSildeNavJRoll.obj === undefined) {
                  return;
              }
              else {
                  oSildeNavJRoll.ReScroll();
              }
          }



        },
        //异步获取优惠券
        getCouponEvent: function () {
            if(oSellerCoupon.length > 0){
                oSellerCoupon.each(function () {
                    $(this).on('click',function () {
                        if(dbTapOff){
                            dbTapOff = false;
                            //异步领取优惠券
                            var couponId = $(this).attr("couponId");
                            G_JSON_GET("/coupon/drawSupplierCoupon", {"couponId": couponId}, function (data) {
                                if (data.status ==="success"){
                                    myPub.TipLayer(data.message,'no',function () {},2)
                                }else {
                                    myPub.TipLayer(data.message,'no',function () {},2)
                                }
                            });
                        }
                        clearTimeout(time_tapOff);
                        time_tapOff = setTimeout(function () {
                            dbTapOff = true;
                        }, 500)
                    });
                })
            }
        },

        //优惠券部分的swiper
        couponSwiper: function () {
            var _this = this;
            _this.mySwiper = new Swiper('.js_sellerCoupon',{
                freeMode : true,
                freeModeMomentumRatio: 0.5,
                observer: true,
                observeParents: true,
                slidesPerView : 'auto',
                lazyLoading: true,
                watchSlidesProgress: true,
                watchSlidesVisibility : true
            })
        },

        //获取商品推荐的商品
        getStoreGoods: function () {
            var _this = this;

            G_JSON_POST(storeGoodsUrl,{supplierId: supplierId},function (res) {
                console.log('99--',res);
                var result = res;
                if(result && result.length > 0){
                    _this.allGoodsList = result;
                    //设置缓存
                    _this.setSession();
                    //加载
                    _this.loadGoodsFn();
                }
            },function (err) {

            })

        },
        
        //滚动加载
        scrollLoad: function () {
            var _this = this;
            
            oContain.off('scroll');
            oContain.on('scroll',function (e) {
                // console.log('lllll',e);
                // var _this = this;
                var oContainScroll = $('.js_contain');
                var minScrHeight = 300;

                var afterScroll = $(this).scrollTop();
                // console.log('jjjj',afterScroll);
                _this.ShowGoTop(afterScroll);
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function () {


                    if(oContainScroll[0].scrollHeight - afterScroll - oContainScroll.height() < minScrHeight){
                        // console.log('jjjjjsss',true);
                        if(_this.tabIndex == 0){
                            if(!_this.loadComplete){
                                console.log('kkkkk');
                                _this.loadGoodsFn();
                            }
                        }

                    }
                },150)
            })
        },

        loadGoodsFn: function () {
            var _this =  this;
            var result = _this.allGoodsList;

            //是否是第一次加载
            if(!_this.firstLoadArr[0]){
                if(result){
                    if(result.length > _this.limit){

                        if((_this.start-1) * _this.limit >= result.length){
                            _this.loadComplete = true;
                            oContain.find('.js_loadingBtn').hide().eq(0).show();
                            return;
                        }else {
                            _this.loadComplete = false;

                            //截取所要加载的数据
                            var nowLoadList = result.slice(_this.start * _this.limit, _this.start*_this.limit+_this.limit);
                            _this.start++;

                            if(result.length > _this.limit * _this.start) {
                                oContain.find('.js_loadingBtn').hide().eq(1).show();
                            }else {
                                oContain.find('.js_loadingBtn').hide().eq(0).show();
                            }

                            oContain.find('.js_goodsList').append(storeHtml.storeGoodsHtml(nowLoadList));

                            myPub.SetImgHeight($('.js_goods_showTwo'));
                            //产品懒加载  异步加载 调用这个
                            lazLoading.DestroyLazLoadingImg();
                            lazLoading.AddLazLoadingImg($('.js_goods_showTwo')[0]);
                        }


                    }
                    else {
                         _this.loadComplete = true;


                        oContain.find('.js_loadingBtn').hide().eq(0).show();
                        oContain.find('.js_goodsList').append(storeHtml.storeGoodsHtml(result));

                        myPub.SetImgHeight($('.js_goods_showTwo'));
                        //产品懒加载  异步加载 调用这个
                        lazLoading.DestroyLazLoadingImg();
                        lazLoading.AddLazLoadingImg($('.js_goods_showTwo')[0]);
                    }
                }
                else {
                    return;
                }
            }
            else {
                _this.firstLoadArr[0] = false;

                if(result && result.length > 0) {
                    oContain.find('.js_storeAllGoods').append(storeHtml.storeRecomHtml());
                    if(result.length > _this.limit){
                        _this.loadComplete =  false;
                        var end = _this.start * _this.limit + _this.limit;
                        var loadGoodsList = result.slice(_this.start, end);
                        _this.start++;

                        oContain.find('.js_loadingBtn').hide().eq(1).show();

                        oContain.find('.js_goodsList').append(storeHtml.storeGoodsHtml(loadGoodsList));

                        myPub.SetImgHeight($('.js_goods_showTwo'));
                        //产品懒加载  异步加载 调用这个
                        lazLoading.DestroyLazLoadingImg();
                        lazLoading.AddLazLoadingImg($('.js_goods_showTwo')[0]);
                    }
                    else {
                        _this.loadComplete =  true;

                        oContain.find('.js_loadingBtn').hide().eq(0).show();

                        oContain.find('.js_goodsList').append(storeHtml.storeGoodsHtml(result));

                        myPub.SetImgHeight($('.js_goods_showTwo'));
                        //产品懒加载  异步加载 调用这个
                        lazLoading.DestroyLazLoadingImg();
                        lazLoading.AddLazLoadingImg($('.js_goods_showTwo')[0]);
                    }
                }
                else {
                    return;
                }
            }
        },
        // 显示回到顶部按钮
        ShowGoTop: function (scrollTop) {
            scrollTop > 300 ? oSideBox.stop().animate({'right': 0}, 300) : oSideBox.stop().animate({'right': '-3.5rem'}, 300);
        },

        //
        setSession: function () {
            var _this = this;
            var data = {supplierId : supplierId, goodsList: _this.allGoodsList};
            sessionStorage.setItem( "supplierObj", JSON.stringify(data) );
        },

        GetSessionData: function () {
            var _this = this;
            var supplierObj = JSON.parse(sessionStorage.getItem('supplierObj'));
            if(supplierObj){
                if(supplierObj.supplierId == supplierId){
                    if(supplierObj.goodsList){
                        _this.allGoodsList = supplierObj.goodsList;
                        _this.loadGoodsFn();
                    }else { return;}
                }
                else {
                    _this.getStoreGoods();
                }
            }
            else {
                _this.getStoreGoods();
            }

        },

        //获取分类的类目
        getStoreCateData: function () {
            var _this = this;
             G_JSON_POST(storeCateUrl,{supplierId: supplierId},function (res) {
                // console.log('jjkjkjkjks---',res);
                var result = res;
                //加载完后更改每一次加载的标识
                _this.firstLoadArr[1] = false;
                if(result.obj){
                    _this.cateGoryList = result.obj;
                    oCateGoryLeftList.append(storeHtml.cateLeftListHtml(result.obj));
                    // 导航加滚动
                    oSildeNavJRoll.AddScroll(oCategorysNavList[0]);
                    oCatesBox.append(storeHtml.cateRightBoxHtml(result.obj));
                }
             })
        }
    };

    var storeHtml = {
        //商店商品列表
        storeGoodsHtml: function (data) {
            var shtml ='';
            for(var i = 0; i < data.length; i++){
                var item = data[i];
                var goodsGueeHtml = item.firstGueeImagePath ? '<img src="'+item.firstGueeImagePath+'" alt="" class="quanpei1"/>' : '';
                var goodsTitle = item.title ? item.title : '';
                shtml +=  '<li>'+
                          '          <a class="BoxSelf" href="'+BASE+'/h/goodspay/goodsView/'+item.goodsSn+'?goodschannel='+item.goodschannel+'">'+
                          '              <figure>'+
                          '                  <img class="js_lazyImg" data-echo="'+HTTP_IMAGE_URL + item.showImage+'?x-oss-process=style/goods_img_3" src="'+BASE+'/static_v3/image/loadImg.jpg">'+
                            goodsGueeHtml+
                           '                 <i class="tip-th" style="display: none;"></i>'+
                           '             </figure>'+
                           '             <aside class="priceArea VBox Bflex1">'+
                           '                 <div class="Bflex1 priceArea_name">'+
                           '                     <h4>'+item.name+'</h4>'+
                           '                     <p class="smallFont_tip">'+goodsTitle+'</p>'+
                           '                 </div>'+
                           '                 <div class="priceArea_price">'+
                           '                     <p class="HBox BoxCenter priceAreaBox">'+

                           '                         <span class="goodsPrice">' +
                           '                               <i>￥</i>'+item.salePrice +
                           '                         </span>'+
                           '                         <span class="goodsWeight Bflex1">/'+item.productName+'</span>'+
                           '                     </p>'+
                           '                 </div>'+
                           '             </aside>'+
                           '         </a>'+
                           '         <p class="addCar js_addCar" pId="'+item.productId+'"><em class="icon-shopcar_small"></em></p>'+
                           '     </li>';
            }
            return shtml;
        },

        //分类右边的列表
        cateRightLiHtml: function (data,fatherSign,fatherId) {
            var shtml = '';
            for(var i = 0; i < data.length; i++){
                var item = data[i];
                shtml +=  '<li class="js_eachProLi jsCategoryRightNav">'+
                          '      <a class="js_appHref jsHrefCategory" data-curidx="0" href="/supplier/supplierGoodsList?supplierId='+ supplierId +'&categoryId='+ item.id +'" data-sign="'+ item.sign +'" data-growing-title="" data-fatherId="'+ fatherId +'" data-id="'+ item.id +'">'+
                          '           <figure>'+
                          '                <img class="swiper-lazy swiper-lazy-loaded" src="'+  HTTP_IMAGE_URL + item.categoryImgPath +'?'+ smallImgArg200 +'" alt="" data-growing-title="">'+
                          '            </figure>'+
                          '            <aside class="priceArea">'+
                          '                <div class="priceArea_name"><h4>'+item.name+'</h4></div>'+
                          '             </aside>'+
                          '       </a>'+
                          '  </li>';
            }

            return shtml;
        },

        //商店商品的父盒子
        storeRecomHtml: function () {
            var shtml = '';
            shtml = '<div class="goods_showChangeBox active js_goods_showTwo marTop_05">'+
                    '     <div class="goods_title HBox">' +
                    '          <h5>商家推荐</h5>' +
                    '     </div>'+
                    '     <div class="goods_showChange">' +
                    '          <ul class="goodsList js_goodsList clearfix">' +
                    '          </ul>'+

                    '      </div>'+
                    '      <div class="moreBtnBox" style="display: none1;">'+                   '           <p class="loadingBtn js_loadingBtn" style="">' +
                    '                <a>没有更多</a>' +
                    '           </p>               ' +
                    '           <p class="loadingBtn js_loadingBtn" style="display: none;">                     ' +
                    '                 <span class="icon_loading icoStyle icon-spinner3 myRotateRefresh"></span> ' +
                    '                 <span>加载中</span> ' +
                    '           </p>            ' +
                    '        </div>'+
                    '</div>';

            return shtml;
        },

        //分类左边的列表
        cateLeftListHtml: function (data) {
            var _this = this;
            var shtml = '';

            for(var i = 0; i < data.length; i++){
                var addClass = i == 0 ? 'active' : '';
                shtml += '<li class="categoryLeftNav js_careCommend '+addClass+'" id="'+data[i].id+'">'+data[i].name+'</li>';
            }
            return shtml;

        },

        cateRightBoxHtml: function (data) {
            var shtml = '';
            var _this = this;
            for(var i = 0; i < data.length; i++){
                var item = data[i];
                var styleHtml = i == 0 ? 'display:block;' : 'display: none;';
                shtml +=  '<div class="categorysDetail js_categorysDetail" style="'+ styleHtml +'">'+
                          '      <div class="swiper-container">'+
                          '            <div class="swiper-wrapper js_wrapperPage">'+
                          '                 <div class="swiper-slide js_slidePageScroll swiper-slide-active">'+
                          '                       <div class="categorysGoods js_categorysGoods">'+
                          '                            <div class="categorysGoods goodsList ListgoodsList ">'+
                          '                                  <ul class="clearfix">'+
                          _this.cateRightLiHtml(item.childCategory, item.sign, item.id)+
                          '                                  </ul>'+
                          '                             </div>'+
                          '                        </div>'+
                          '                  </div>'+
                          '              </div>'+
                          '         </div>'+
                          '</div>';
            }

            return shtml;
        }
    };

});